package fun.stgoder.easydarwin.jobs.bl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import fun.stgoder.easydarwin.jobs.bl.entity.Job;
import fun.stgoder.easydarwin.jobs.bl.executor.CleanupExecutor;
import fun.stgoder.easydarwin.jobs.bl.executor.MergeFileExecutor;
import fun.stgoder.easydarwin.jobs.comm.Constants;
import fun.stgoder.easydarwin.jobs.comm.util.SqlUtil;

@Component
public class CommonScheduler {

    private final Logger logger = LoggerFactory.getLogger(CommonScheduler.class);

    @Scheduled(fixedDelay = 5000, initialDelay = 22000)
    public void doJobs() {
        try {
            // find waiting jobs
            List<Job> waitingJobs = SqlUtil.select(
                    "select " + Job.BASE_COLS + " from job where status = 0",
                    Job.class);

            // stop job and merge file
            for (Job job : waitingJobs) {

                if (job.getLendTime() < System.currentTimeMillis()) { // check time
                    if (Constants.TEST_MODE)
                        logger.info("do job now: " + job.toString());

                    MergeFileExecutor.INSTANCE.execute(job);
                } else {
                    if (Constants.TEST_MODE)
                        logger.info("do job later: " + job.toString());
                }

            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @Scheduled(fixedDelay = 1000 * 60 * 5, initialDelay = 11000)
    public void cleanupTsFiles() {
        CleanupExecutor.INSTANCE.execute();
    }
}
